$(document).ready(function () {
    // 无子菜单
    $(".navigation a").bind("click", clickSubMenu);
    var pathName = window.location.pathname;// 浏览器路径
    var a = $('a[href="' + pathName + '"]');
    a.closest('ul').show();
    a.closest('li').addClass("navigation__active");
    // 有子菜单
    $(".navigation__sub a").bind("click", clickMainMenu);
    // pjax timeout 配置
    $.pjax.defaults.timeout = 5000;

    // data-pjax 属性与 a 标签组合选择器绑定 pjax，例如分页链接、操作按钮
    $(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container', {type: 'post'});


    $(document).on('submit', 'form[data-pjax]', function (event) {
        $.pjax.submit(event, '#pjax-container', {'type': 'post'});
    });
    // 菜单滚动
    if ($('.scrollbar-inner')[0]) {
        $('.scrollbar-inner').scrollbar().scrollLock();
    }

    /**
     * form 表单提交
     */
    $(document).off('submit', 'form[data-pjax]').on('submit', 'form[data-pjax]', function (event) {
        $.pjax.submit(event, '#pjax-container', {'type': 'post'})
    });


    // 进度条效果
    // NProgress.configure({ showSpinner: false });
    $(document).on('pjax:start', function () {
        NProgress.start();
    });
    $(document).on('pjax:end', function () {
        NProgress.done();
    });

    // 设置当前选中菜单
    setCurrentAdminMenu();
    // 折叠其他展开菜单
    clickMenuFold();
    // 初始化加载菜单
    var firstChild = $('#tax_menu >div').children('a').first();
    // 加载模块
    sys_model(firstChild.attr("value"));
});

/**
 * 折叠其他展开菜单
 */
function clickMenuFold() {
// 折叠其他展开菜单
    $(".navigation>li>a").click(function () {
        var message = $(".navigation>li>a").closest("li").not('.navigation__active');
        $.each(message, function (i, v) {
            if (!$(v).children('ul').is(":hidden")) {
                $(v).children('ul').slideToggle();
            }
        })
    })
}

/**
 * 点击主菜单动画效果
 */
function clickMainMenu(event) {
    event.preventDefault();	// 取代 return false 防止页面跳转
    var $this = $(this);
    $(".navigation a").parent().removeClass("navigation__active navigation__sub--toggled");
    $(".navigation__active").removeClass("navigation__active");
    $this.parent().addClass("navigation__active");
}

/**
 * 点击子菜单
 */
function clickSubMenu(event) {
    event.preventDefault();	// 取代 return false 防止页面跳转
    var $this = $(this);
    var url = $this.attr("href");
    if (url.substring(0, 1) == '/') {
        sendPjax(url, "#pjax-container");
    }
    $(".navigation__sub a").parent().removeClass("navigation__active");
    $(".navigation__active").removeClass("navigation__active");
    $this.parent().addClass("navigation__active");
}

/**
 * 发送 pjax url：后台 action container：承载响应内容的容器 extData：扩展数据，可以在 pajx 事件回调方法中通过
 * options.extData 获取 例如：$(document).on('pjax:success', function(event, data,
 * status, xhr, options)
 */
function sendPjax(url, container, extData) {
    $.pjax({
        url: url
        , container: container
        , extData: extData
        , type: "POST"
    });
}

/**
 * 设置当前选中菜单
 */
function setCurrentAdminMenu() {
    var pathName = location.pathname;
    if (pathName == '/admin') {
        $(".jfa-main-menu[home='true']").addClass("jfa-cur-menu");
        return false;
    }

    $(".jfa-sub-menu a[href]").each(function (index, element) {
        var href = $(element).attr("href");
        if (href != '/admin' && pathName.indexOf(href) != -1) {
            var currentMenu = $(".jfa-sub-menu a[href='" + href + "']");
            currentMenu.addClass("jfa-cur-menu");
            return false;	// return false 终止后续循环，提升效率
        }
    });
}


function initSwitchInput(prepareAction) {
    var switchInput = $("input.toggle-switch__checkbox");

    // 锁定开关绑定事件
    switchInput.on("click", function (event) {
        var $this = $(event.target);	// 或者 $(this)
        var state = $this.get(0).checked ? true : false;
        var action = prepareAction($this, state);
        $.ajax(action.url, {
            type: "POST"
            , cache: false
            , dataType: "json"
            , data: action.data
            , error: function (ret) {
                showMsg(3, ret.msg);
                resetCheckInput($this);
            }
            , success: function (ret) {
                if (ret.state == "fail") {
                    showMsg(3, ret.msg);
                    resetCheckInput($this);
                } else {
                    showMsg(0, ret.msg);
                }
            }
        });
    });
}


/**
 * magic input 组件触发 ajax 请求失败后复位到上一个状态
 */
function resetCheckInput($checkbox) {
    var checkbox = $checkbox.get(0);
    checkbox.checked = !checkbox.checked;
}

function ajaxSubmit(postUrl, data, sucUrl) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: postUrl,
        data: data,
        success: function (ret) {
            if (ret.state == 'ok') {
                location.href = sucUrl;
                return;
            } else {
                showMsg(2, ret.msg);
                return;
            }
        },
        error: function () {
            alert("异常！");
        }
    });
}

function kPost(url,pjaxUrl){
    $.post(url,function (ret) {
        showRetMsg(ret,pjaxUrl);
    })
}

function kpjax(url) {
    $.pjax({url: url, container: '#pjax-container'});
}



function showRetMsg(ret, url) {
    toastr.options = {
        "closeButton": true, // 是否显示关闭按钮
        "debug": false, // 是否使用debug模式
        "progressBar": true,// 显示进度条
        "positionClass": "toast-bottom-right",// 弹出窗的位置 右下
        "showDuration": "300",// 显示的动画时间
        "hideDuration": "1000",// 消失的动画时间
        "timeOut": "5000", // 展现时间
        "extendedTimeOut": "1000",// 加长展示时间
        "showEasing": "swing",// 显示时的动画缓冲方式
        "hideEasing": "linear",// 消失时的动画缓冲方式
        "showMethod": "fadeIn",// 显示时的动画方式
        "hideMethod": "fadeOut" // 消失时的动画方式
    };
    if (ret.state == 'ok') {
        toastr.success(ret.msg, "成功通知");
        if (!isEmpty(url)) {
            $.pjax({url: url, container: '#pjax-container'});
        }
    } else {
        toastr.error(ret.msg, "错误通知");
    }

}

function showMsg(type, msg) {
    toastr.options = {
        "closeButton": true, // 是否显示关闭按钮
        "debug": false, // 是否使用debug模式
        "progressBar": true,// 显示进度条
        "positionClass": "toast-bottom-right",// 弹出窗的位置 右下
        "showDuration": "300",// 显示的动画时间
        "hideDuration": "1000",// 消失的动画时间
        "timeOut": "5000", // 展现时间
        "extendedTimeOut": "1000",// 加长展示时间
        "showEasing": "swing",// 显示时的动画缓冲方式
        "hideEasing": "linear",// 消失时的动画缓冲方式
        "showMethod": "fadeIn",// 显示时的动画方式
        "hideMethod": "fadeOut" // 消失时的动画方式
    };

    if (type == "success" || type == 0) {// 成功
        toastr.success(msg, "成功通知");
    } else if (type == "info" || type == 1) {// 提示
        toastr.info(msg, "提示通知");
    } else if (type == "warning" || type == 2) {// 警告
        toastr.warning(msg, "警告通知");
    } else if (type == "error" || type == 3) {// 错误
        toastr.error(msg, "错误通知");
    } else if (type == "clear" || type == 4) {// 清除
        toastr.clear();
    }
}

function ready(model, p, s, modelId) {
    $(document).ready(function () {
        $("#jmisForm").ajaxForm({
            dataType: "json"
            , beforeSubmit: function (formData, jqForm, options) {
            }
            , success: function (ret) {
                if (ret.state == "ok") {
                    showMsg(0, ret.msg);
                    var url;
                    if (typeof (modelId) == "undefined") {
                        url = "/admin/" + model + "/addOrEdit?p=" + p + "&s=" + s;
                    } else {
                        url = "/admin/" + model + "/addOrEdit?p=" + p + "&s=" + s + "&id=" + modelId;
                    }
                    $.pjax({url: url, container: '#pjax-container'});
                } else {
                    showMsg(3, ret.msg)
                }
            }
            , error: function (ret) {
                showMsg(3, ret.statusText)
            }
            , complete: function (ret) {
            }
        });
    });
}

function stop() {
    return false;
}

document.oncontextmenu = stop;

function clear() {
    Source = document.body.firstChild.data;
    document.open();
    document.close();
    document.body.innerHTML = Source;
}

function sdmForm(url, parems) {
    $("#jmisForm").ajaxForm({
        dataType: "json"
        , beforeSubmit: function (formData, jqForm, options) {
        }
        , success: function (ret) {
            if (ret.state == "ok") {
                showMsg(0, ret.msg);
                if (!isEmpty(parems)) {
                    $.pjax({url: url, container: '#pjax-container'});
                }
            } else {
                showMsg(3, ret.msg);
                return;
            }
        }
        , error: function (ret) {
            showMsg(3, ret.statusText);
            return;
        }
        , complete: function (ret) {
        }
    });
}

var websocket;
var socketStatus;

function buildSocket(){
    let url = null;
    let username = $(".user__name").data("nick");

    let ishttps = 'https:' == document.location.protocol ? true : false;

    if(ishttps){
        url = 'wss://' + window.location.host + '/socket.ws?username='+username
    }else{
        url = 'ws://' + window.location.host + '/socket.ws?username='+username;
    }
    if ('WebSocket' in window) {
        websocket = new ReconnectingWebSocket(url,null,{"reconnectInterval":5000,"maxReconnectInterval":50000});
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket(url);
    } else {
        websocket = new SockJS(url);
    }
}

buildSocket();//创建websocket连接

websocket.onopen = function (evnt) {
    socketStatus=true;
    showMsg(0, "已连接服务器！")
};

websocket.onmessage = function (evnt) {
    let json = JSON.parse(event.data);
    console.info(json+"*******************")
    console.info(json);
    console.info(json.category);
    console.info(json.msg);

    if (json.category == "ciisdata") {
        showMsg(0, "获取消息成功");
    }else if (json.category == "issued") {
        showMsg(0, json.msg);
    }else if (json.category === "debug" ){
        debugMsg(json);
    }else if(json.msg != undefined && json.msg != ''){
        showMsg(3, json.msg);

        if(json.code != undefined && parseInt(json.code) ==401){//登录信息失效。跳转到登录页面
            setTimeout(function () {
                window.location.href="/login";
            },5000);

        }

way.set('debug_list',[]);
    }
};

websocket.onerror = function (evnt) {
    socketStatus=false;
    showMsg(3, "连接错误")
};
websocket.onclose = function (evnt) {
    socketStatus=false;
    showMsg(3, "服务器断开连接！");
};

/**
 * 处理实时调试数据
 * @param msg
 */
function debugMsg(msg){
    let htmlEle="<div class='listview__item'>" +
        "<div class='listview__content'>" +
        "<div class='listview__heading'>";
        if(msg.isDownload){
            htmlEle += "<i class='zmdi zmdi-download zmdi-hc-fw' style='color: #00B83F'></i>服务器接收数据 ";
        }else{
            htmlEle += "<i class='zmdi zmdi-upload zmdi-hc-fw' style='color: #00aced'></i>服务器发送数据 ";
        }
        htmlEle += msg.date
        htmlEle += "数据长度 ";
        htmlEle += msg.msg.length/2;
        htmlEle += "</div><p>[";
        let n = 2;
        for (let i = 0, l = msg.msg.length; i < l/n; i++) {
            htmlEle += (msg.msg.slice(n*i, n*(i+1))+" ");
        }

        htmlEle += "]</p></div></div>";
    $("#debug_msg").find(".listview").append(htmlEle);
}

/**
 * 点击系统加载模块内容
 *
 * @param evn
 */
function sys_model(evn, name) {

    if (isEmpty(evn)) {
        evn = 1;
    }
    $.post('/admin/sys/menu/findMenuModel', {taxId: evn}, function (data) {
        var html = '';
        if (typeof data == "string") {
            location.href = "/login";
            return;
        }
        var identif = data.data.taxonomy.identification;
        $.each(data.data.data, function (i, v) {
            html += '<li class="nav-item"><a class="nav-link active text-white" href="javascript:void(0)" onclick="model_menu(' + v.id + ',&quot;' + identif + '&quot;)" value="' + v.id + '"><i class="' + v.icon + '"></i>' + v.name + '</a></li>';
        })
        $('#nav_menu').html(html);
        model_();
        // 加载菜单
        model_menu(data.data.data[0].id, identif);
        if (!isEmpty(name)) {
            $("#setting").html($("#settingName").val() + name);
        }
    })
}

/**
 * 点击模块加载菜单
 */
function model_menu(id, identif) {
    $.post('/admin/sys/menu/menuSwitch', {id: id}, function (data) {
        var html = '<li><a data-pjax="" href="/admin/' + identif + '"><i class="zmdi zmdi-home"></i> 主页</a></li>';
        if (typeof data == "string") {
            location.href = "/login";
        }
        $.each(data, function (i, v) {
            if (v[0].superior > 0) {
                // 一级菜单有下级菜单
                html += '<li class="navigation__sub">\n' +
                    '                <a href=""><i class="' + v[0].superiorIcon + '"></i>' + i + '<span class="badge badge-pill badge-info">' + v.length + '</span></a>\n' +
                    '                <ul>\n';
                $.each(v, function (a, b) {
                    html += '<li><a data-pjax href="' + (b.url === '\'/\'' ? 'javascript:void(0)' : b.url) + '">' + b.name + '</a></li>\n';
                });
                html += '</ul></li>';
            } else {
                html += '<li><a  data-pjax href="' + (v[0].url === '\'/\'' ? 'javascript:void(0)' : v[0].url) + '"><i class="' + v[0].icon + '"></i> ' + i + '</a></li>';
            }
        })
        $('#navigation_menu').html(html);
        // 无子菜单
        $(".navigation li a").bind("click", clickSubMenu);
        // 有子菜单
        $(".navigation__sub a").bind("click", clickMainMenu);
        var chil = $(".navigation li").children(), href = chil.attr("href");
        if (href == "" || href == "/") {
            href = chil.next().find("a").attr("href");
        }
        // kpjax("/admin/erp/erppurchase?type=0");//测试代码
        if (window.location.pathname != href) {
            kpjax(href);
        }
        // 折叠其他菜单
        clickMenuFold();
    })
}

/**
 * 模块左右滑动
 */
function model_() {
    var left = 0, l = $("#left"), r = $("#right"), m = $("#nav_menu"), menu_width = 0,
        div_width = m.parent().width() - 100, ch = m.children();
    for (var ch1 of ch) {
        menu_width += $(ch1).width();
    }
    window.onresize = function () {
        div_width = m.parent().width() - 100;
        left = 0;
        m.css("left", left);
        l.attr("disabled", "disabled");
        r.removeAttr("disabled");
        if (menu_width >= div_width + 100) {
            l.show();
            r.show();
        } else {
            l.hide();
            r.hide();
        }
    };
    m.width(menu_width);
    if (menu_width >= div_width + 100) {
        l.show();
        r.show();
    } else {
        l.hide();
        r.hide();
    }
    l.attr("disabled", "disabled");
    // 向左
    l.click(function () {
        r.removeAttr("disabled");
        l.attr("disabled", "disabled");
        left = parseInt(m.css("left"));
        if (left >= 0) {
            return false;
        }
        left += div_width;
        m.animate({left: left + "px"}, "slow", function () {
            if (left <= 0) {
                l.removeAttr("disabled");
            }
        });
    })
    // 向右
    r.click(function () {
        l.removeAttr("disabled");
        r.attr("disabled", "disabled");
        var ul = m.children().length * 112 - div_width;
        if (Math.abs(left) >= ul) {
            return false;
        }
        left = parseInt(m.css("left"));
        left -= div_width;
        m.animate({left: left + "px"}, "slow", function () {
            if (Math.abs(left) <= ul) {
                r.removeAttr("disabled");
            }
        });
    })
}

// 判断是否为空
function isEmpty(v) {
    switch (typeof v) {
        case 'undefined':
            return true;
        case 'string':
            if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
            break;
        case 'boolean':
            if (!v) return true;
            break;
        case 'number':
            if (0 === v || isNaN(v)) return true;
            break;
        case 'object':
            if (null === v || v.length === 0) return true;
            for (var i in v) {
                return false;
            }
            return true;
    }
    return false;
}

function select2OnLoad() {
    if ($("select.select2")[0]) {
        $("select.select2").select2({
            dropdownAutoWidth: !0, width: "100%",
            dropdownParent: $(".select2-parent")[0] ? $(".select2-parent") : $("body")
        })
    }
}



/** ********************************SELECT多级输出*****************************************/
function TreeSelector(item, data, rootId) {
    this._data = data;
    this._item = item;
    this._rootId = rootId;
}

TreeSelector.prototype.createTree = function (par) {
    var len = this._data.length;
    for (var i = 0; i < len; i++) {
        if (this._data[i].pid == this._rootId) {
            this._item.options.add(new Option("" + this._data[i].text, this._data[i].id));
            for (var j = 0; j < len; j++) {
                this.createSubOption(len, this._data[i], this._data[j], par);
            }
        }
    }
}
TreeSelector.prototype.createSubOption = function (len, current, next, par) {
    var blank = "....";
    if (next.pid == current.id) {
        intLevel = 0;
        var intlvl = this.getLevel(this._data, this._rootId, current);
        for (a = 0; a < intlvl; a++)
            blank += "....";
        blank += "|--";
        this._item.options.add(new Option(blank + next.text, next.id));
        if (next.id + '' === par) {
            $(this._item.options).attr("selected", "selected");
        }
        for (var j = 0; j < len; j++) {
            this.createSubOption(len, next, this._data[j]);
        }
    }
}
TreeSelector.prototype.getLevel = function (datasources, topId, currentitem) {
    var pid = currentitem.pid;
    if (pid != topId) {
        for (var i = 0; i < datasources.length; i++) {
            if (datasources[i].id == pid) {
                intLevel++;
                this.getLevel(datasources, topId, datasources[i]);
            }
        }
    }
    return intLevel;
}
/** ********************************SELECT多级输出*****************************************/